﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;

namespace SpaceEngineersSaveEditor
{
    /// <summary>
    /// Interaction logic for ObjectsWindow.xaml
    /// </summary>
    public partial class ObjectsWindow : Window
    {
        public ObjectsWindow()
        {
            InitializeComponent();
        }

        public ObjectsWindow(World selectedWorld) : this()
        {
            WindowHeader = string.Format("Objects in {0}", selectedWorld.WorldName);

            LoadObjects(selectedWorld);

            DataContext = this;
        }

        private void LoadObjects(World selectedWorld)
        {
            var worldFiles = Directory.EnumerateFiles(selectedWorld.WorldPath);

            var sbsFile = selectedWorld.WorldPath + Path.DirectorySeparatorChar + "SANDBOX_0_0_0_.sbs";

            if (File.Exists(sbsFile))
            {
                ParseFileIntoWorldObjects(sbsFile);
            }
            else
            {
                var errorMessage = string.Format("File not found: {0}", sbsFile);
                throw new ApplicationException(errorMessage);
            }
        }

        public void ParseFileIntoWorldObjects(string sbsFile)
        {
            var serializer = new XmlSerializer(typeof(MyObjectBuilder_Sector));
            
            Console.WriteLine("deserializing...");
            var reader = new StreamReader(sbsFile);
            var myObjectBuilderSector = (MyObjectBuilder_Sector)serializer.Deserialize(reader);

            Console.WriteLine("done");
        }

        public String WindowHeader { get; set; }
        public WorldObject WorldObjects { get; set; }
    }
}
